import sys
import os
import sys
import time
import abc as hou
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *

# import hou
import socket

import threading

#
# import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
#
#
#     def localRequest(host, port, buffer, msg):
#         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#         sock.connect((host, port))
#         # sock.listen(0)
#         sock.send(msg)
#         res = sock.recv(buffer)
#         # back=res.encode('utf-8').decode('unicode_escape')
#         # back=res.decode('utf-8')
#         # back=res.encode('utf-8')
#         back = res.decode('utf-8').encode('gbk')
#
#         if back.startswith('MZdo'):  # do action
#             # re = exec(back[4:])
#             print
#             back
#             exec(back[4:])
#         else:  # chat
#             print
#             back
#             chat = 'print back'
#             exec(chat)
#
#
#     def sub(*args):
#         hostname = socket.gethostname()
#         ip = socket.gethostbyname(hostname)
#         HOST = '192.168.0.105'
#         PORT = 9527
#         BUFFER = 4096
#
#         key = hou.pwd().parm('key').evalAsString()
#         com = hou.pwd().parm('command').evalAsString()
#
#         data = {'key': key, 'ip': ip, 'command': com}
#         msg = str(data)
#         clientThread = threading.Thread(target=localRequest, args=(HOST, PORT, BUFFER, msg))
#         # clientThread.setDaemon(True)
#         clientThread.start()

class Server(QThread):
    # s=Q
    def __init__(self,istart):
        super(Server, self).__init__()
        # self.HOST = '192.168.0.113'
        self.HOST = '192.168.1.85'
        # self.HOST='127.0.0.1'
        self.PORT = 2021
        self.BUFFER = 10240
        self.istart=istart
        self.root=hou.node('/obj')
    # sky
    def check_sky(self):
        sky_node=''
        for i in self.root.children():
            if 'Sky' in i.name() and i.type().name()=='envlight':
                sky_node=i
        if not sky_node:
            sky_node=self.root.createNode('envlight','Sky')
        return sky_node

    def sky(self,data):
        sky_node=self.check_sky()
        sky_node.parm('env_map').set(data['attr']['path'])

    # building
    def check_building(self):
        pass

    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind((self.HOST, self.PORT))
        sock.listen(100)
        print('servering listening')
        while self.istart>0:
            time.sleep(0.1)
            print('OK')
            try:
                client_sock, client_addr = sock.accept()
                recv = client_sock.recv(self.BUFFER)
                if recv:
                    data = eval(recv)
                    print(data)
                    if data['attr']['img_type']=='sky':
                        self.sky(data)
                    elif data['attr']['img_type']=='building':
                        self.building(data)
                    back_data={'stauts':'success'}
                    client_sock.send(str(back_data).encode())
            except Exception as runServer_ERR:
                print(str(runServer_ERR))


        # sock.close()


class GC(QWidget):

    def __init__(self):
        super(GC, self).__init__()
        #self.IMG_PATH=os.path.join(os.path.dirname(__file__),'imgs')

        self.istart=-1

        self.setWindowTitle(('GC归藏智能推演'))
        self.main_layout=QVBoxLayout()
        self.main_layout.setSpacing(50)
        self.frame=QFrame()
        self.frame_layout=QHBoxLayout()
        self.cgai=QLabel()
        self.cgai.setScaledContents(True)
        #self.cgai.setPixmap(QPixmap(os.path.join(self.IMG_PATH,'CGAI.png')))
        #self.cgai.setFixedSize(QSize(80,80))
        label_font=QFont('',25,75)
        self.label=QLabel('GC(归藏)智能推演系统')
        self.label.setFont(label_font)
        #self.frame_layout.addWidget(self.cgai)
        self.frame_layout.addWidget(self.label)
        self.frame.setLayout(self.frame_layout)

        self.on_style="color:#00FF00;font-size:25"
        self.stop_style="color : #CDC9C9;font-size:25"
        self.btn_layout=QVBoxLayout()
        self.btn_layout.setContentsMargins(50,20,50,50)
        self.listen_btn=QPushButton('运行')
        btn_font=QFont('',18,50)
        self.listen_btn.setFont(btn_font)
        self.listen_btn.setStyleSheet(self.stop_style)
        self.listen_btn.setMinimumHeight(80)
        self.listen_btn.clicked.connect(self._start)
        self.btn_layout.addWidget(self.listen_btn)
        self.main_layout.addWidget(self.frame)
        self.main_layout.addLayout(self.btn_layout)
        self.setLayout(self.main_layout)

        self.server=Server(self.istart)


    def _start(self):
        if self.istart==-1:
            self.listen_btn.setStyleSheet(self.on_style)
            self.istart*=-1
            self.server.istart=1
            self.server.start()
        else:
            self.istart *= -1
            self.listen_btn.setStyleSheet(self.stop_style)
            self.server.istart=0

if __name__ == '__main__':
    # HOST = '122.112.151.201'  # 云ip
    HOST='192.168.1.222'

    # PORT = 9527
    # BUFFER = 10240
    # mys = InfoServer()
    # mys.runServer(HOST, PORT, BUFFER)
    app=QApplication(sys.argv)
    gc=GC()
    gc.show()
    sys.exit(app.exec_())